package com.ljy.common.shcedule;

import java.util.HashMap;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.ljy.common.shcedule.task.ScheduledJob;
import com.ljy.common.shcedule.task.ScheduledJob2;
import com.ljy.common.shcedule.task.ScheduledJobAll;
import com.ljy.common.util.JsonUtil;


@Component
public class MyScheduler {
	@Autowired
    private Scheduler scheduler;
    
    public void scheduleJobs() throws SchedulerException {
//        startJob1(scheduler); 
//        startJob2(scheduler); 
        startJob3(scheduler); 
    }
    private void startJob1(Scheduler scheduler) throws SchedulerException{
        JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class) .withIdentity("job1", "group1").build(); 
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?"); 
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1") .withSchedule(scheduleBuilder).build(); 
        scheduler.scheduleJob(jobDetail,cronTrigger); 
    } 
    private void startJob2(Scheduler scheduler) throws SchedulerException{ 
        JobDetail jobDetail = JobBuilder.newJob(ScheduledJob2.class) .withIdentity("job2", "group1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?"); 
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger2", "group1") .withSchedule(scheduleBuilder).build(); 
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }
    
    /**
     * 通过反射执行任务类
     * @param scheduler
     * @throws SchedulerException
     */
    private void startJob3(Scheduler scheduler) throws SchedulerException{ 
    	
        JobDetail jobDetail = JobBuilder.newJob(ScheduledJobAll.class) .withIdentity("job3", "group1").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ?"); 
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger3", "group1") .withSchedule(scheduleBuilder).build(); 
      //放入参数，运行时的方法可以获取
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("beanName", "Task1"); 
        map.put("method", "test"); 
        map.put("param", "我是参数"); 
        
        jobDetail.getJobDataMap().put("JOB_PARAM_KEY", JsonUtil.toJson(map));
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }
}
